#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <iostream>
#include <functional>
#include <muduo/base/Timestamp.h>
#include <string>

using namespace std;
using namespace muduo::net;
using namespace placeholders;
using namespace muduo;

class ChatServer
{
public:
    ChatServer(EventLoop* loop,
            const InetAddress& listenAddr, //IP+Port
            const string& nameArg) // 服务器名字
            :m_server(loop,listenAddr,nameArg),m_pLoop(loop)
            {
                //给服务器注册用户连接创建和断开回调
                m_server.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));
                //给服务器注册用户读写事件回调
                m_server.setMessageCallback(std::bind(&ChatServer::onMessage,this,_1,_2,_3));
                //设置线程数量,1个I/O，三个worker线程，会自动划分线程
                m_server.setThreadNum(4);
            }
    //开启事件循环
    void start()
    {
        m_server.start();
    }
private: 
    //处理连接断开 
    void onConnection(const TcpConnectionPtr& conn)
    {
        if(conn->connected())
          cout<<conn->peerAddress().toIpPort()<<"->"<<conn->localAddress().toIpPort()<<"line"<<endl;
        else
        {
            cout<<conn->peerAddress().toIpPort()<<"->"<<conn->localAddress().toIpPort()<<"offine"<<endl;
            conn->shutdown(); //close(fd)
        }
    }
    //处理读写事件
    void onMessage(const TcpConnectionPtr& conn, //
                            Buffer* buf,
                            Timestamp time)
    {
         string sbuf = buf->retrieveAllAsString();
         cout<<"recv "<<sbuf<<" time "<<time.toString()<<endl;
         conn->send(sbuf);
    }
private:
    TcpServer m_server;
    EventLoop* m_pLoop; //EventLoop循环指针

};

int main()
{
    EventLoop loop; // epoll
    InetAddress addr("127.0.0.1",6000);

    ChatServer server(&loop,addr,"ChatServer");
    server.start();
    loop.loop();  //epoll_wait，以阻塞方式等待新用户连接
    return 0;
}